﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using log4net;
using System.Reflection;
using System.Configuration;
using Subtle.Domain.Services.Interfaces;

namespace Subtle.Domain.Services
{
	/// <summary>
	/// Email Service
	/// </summary>
	public class EmailService : IEmailService
	{
		private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		private string defaultFrom;
		private string smtpServer;
		private string smtpUsername;
		private string smtpPassword;

		/// <summary>
		/// Email Service
		/// </summary>
		public EmailService()
		{
			if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["AdminEmail"]))
			{
				throw new ConfigurationErrorsException("AdminEmail does not exist in the configuration");
			}
			if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["SMTPServer"]))
			{
				throw new ConfigurationErrorsException("SMTPServer does not exist in the configuration");
			}
			if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["SMTPUsername"]))
			{
				throw new ConfigurationErrorsException("SMTPServer does not exist in the configuration");
			}
			if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["SMTPPassword"]))
			{
				throw new ConfigurationErrorsException("SMTPServer does not exist in the configuration");
			} 

			this.defaultFrom = ConfigurationManager.AppSettings["AdminEmail"];
			this.smtpServer = ConfigurationManager.AppSettings["SMTPServer"];
			this.smtpUsername = ConfigurationManager.AppSettings["SMTPUsername"];
			this.smtpPassword = ConfigurationManager.AppSettings["SMTPPassword"];
		}

		/// <summary>
		/// Send
		/// </summary>
		/// <param name="to"></param>
		/// <param name="from">Leave blank if you want to use the default from email address</param>
		/// <param name="subject"></param>
		/// <param name="body"></param>
		/// <returns>Returns true if the email was sent succesfully</returns>
		public bool Send(string to, string from, string subject, string body)
		{
			if (String.IsNullOrEmpty(from))
			{
				from = defaultFrom;
			}
			MailMessage email = new MailMessage(
			   from,
			   to
			);
			email.Subject = subject;
			email.Body = body;
			SmtpClient smtp = new SmtpClient(smtpServer, 25);
			smtp.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
			smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

			try
			{
				smtp.Send(email);
			}
			catch (SmtpException ex)
			{
				logger.Error(ex);
				return false;
			}
			return true;
		}
	}
}
